export interface IBuff {
    Uid: number;
    Color: string;
    Value: number;

    Elapsed: number;
    TotalElapsed: number;
    Duration: number;
    Interval: number;
}

export class BuffHolder {
    private buffs: IBuff[] = [];
    private cb: Function;
    private target: any;

    public AddBuff(uid: number, color: string, value: number, duration: number, interval: number) {
        let buff = this.buffs.find(b => b.Uid === uid);
        if (buff) {
            buff.Value = value;
            buff.Duration = duration;
            buff.Interval = interval;
            buff.Elapsed = 0;
            buff.TotalElapsed = 0;
        } else {
            this.buffs.push({
                Uid: uid,
                Color: color,
                Value: value,
                Duration: duration,
                Interval: interval,
                Elapsed: 0,
                TotalElapsed: 0
            });
        }
    }

    public onCallBack(cb: Function, target?: any) {
        this.cb = cb;
        this.target = target;
    }

    public RemoveBuff(uid: number) {
        let index = this.buffs.findIndex(b => b.Uid === uid);
        if (index >= -1) {
            this.buffs.splice(index, 1);
        }
    }

    public update(deltaTime: number) {
        for (let i = 0; i < this.buffs.length; i++) {
            let buff = this.buffs[i];
            buff.Elapsed += deltaTime;
            buff.TotalElapsed += deltaTime;

            if (buff.Elapsed >= buff.Interval) {
                buff.Elapsed = 0;
                this.cb && this.cb.call(this.target, [buff.Uid, buff.Color, buff.Value]);
            }

            if (buff.TotalElapsed >= buff.Duration) {
                this.RemoveBuff(buff.Uid);
                i--;
            }
        }
    }

}

